package db

import (
	"fmt"
	"manage-server/global"
	"manage-server/model/gv_global"
	"manage-server/model/manage_model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var ManageDB *gorm.DB
var ImDB *gorm.DB
var GlobalDB *gorm.DB

func InitDB() {
	// im database
	imDSN := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s",
		global.App.Config.Mysql.MysqlIM.UserName,
		global.App.Config.Mysql.MysqlIM.Passowrd,
		global.App.Config.Mysql.MysqlIM.Host,
		global.App.Config.Mysql.MysqlIM.Port,
		global.App.Config.Mysql.MysqlIM.Database,
		global.App.Config.Mysql.MysqlIM.Charset,
		global.App.Config.Mysql.MysqlIM.ParseTime,
		global.App.Config.Mysql.MysqlIM.Loc,
	)
	// manage databse
	manageDSN := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s",
		global.App.Config.Mysql.MysqlManage.UserName,
		global.App.Config.Mysql.MysqlManage.Passowrd,
		global.App.Config.Mysql.MysqlManage.Host,
		global.App.Config.Mysql.MysqlManage.Port,
		global.App.Config.Mysql.MysqlManage.Database,
		global.App.Config.Mysql.MysqlManage.Charset,
		global.App.Config.Mysql.MysqlManage.ParseTime,
		global.App.Config.Mysql.MysqlManage.Loc,
	)
	globalDSN := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s",
		global.App.Config.Mysql.MysqlGlobal.UserName,
		global.App.Config.Mysql.MysqlGlobal.Passowrd,
		global.App.Config.Mysql.MysqlGlobal.Host,
		global.App.Config.Mysql.MysqlGlobal.Port,
		global.App.Config.Mysql.MysqlGlobal.Database,
		global.App.Config.Mysql.MysqlGlobal.Charset,
		global.App.Config.Mysql.MysqlGlobal.ParseTime,
		global.App.Config.Mysql.MysqlGlobal.Loc,
	)
	imdb, erri := gorm.Open(mysql.Open(imDSN), &gorm.Config{})
	managedb, errm := gorm.Open(mysql.Open(manageDSN), &gorm.Config{})
	globaldb, errg := gorm.Open(mysql.Open(globalDSN), &gorm.Config{})
	if erri != nil {
		panic(fmt.Sprintf("初始化数据库失败: %s", erri))
	}
	if errm != nil {
		panic(fmt.Sprintf("初始化数据库失败: %s", errm))
	}
	if errg != nil {
		panic(fmt.Sprintf("初始化数据库失败: %s", errg))
	}
	ImDB = imdb
	ManageDB = managedb
	GlobalDB = globaldb
	// 后台数据库迁移
	ManageDB.AutoMigrate(
		&manage_model.ManageUser{},
		&manage_model.ManageUserRole{},
		&manage_model.ManageLoginLog{},
	)
	// 全局数据库迁移
	GlobalDB.AutoMigrate(
		&gv_global.GlobalParamConfig{},
	)
}

func GetImDB() *gorm.DB {
	return ImDB
}

func GetManageDB() *gorm.DB {
	return ManageDB
}
